#include "qwgraphicsview.h"

QWGraphicsView::QWGraphicsView(QWidget *parent):QGraphicsView(parent)   // 如果使用了提升类，则按这种模式写构造函数
{
    zoomFactor=1.0;
    endPoint=QPoint(0,0);
    startPoint=QPoint(0,0);

//    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隐藏水平条
//    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隐藏竖条
    /*使用QGraphicsView类的设置属性函数.在构造函数中增加下面两个函数即可实现图像以鼠标中心点缩放*/
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorUnderMouse);
}

void QWGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    QPoint point=event->pos();  // QGraphicsView的坐标

    if(isMousePressed)
    {
        endPoint=event->pos();   // 按下鼠标左键移动，则会实时更新endPoint

    }
    //else
    {
        emit mouseMovePoint(point,endPoint,startPoint);

    }
    QGraphicsView::mouseMoveEvent(event);
}

void QWGraphicsView::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton)
    {
        QPoint point=event->pos();   // QGraphicsView的坐标
       // emit mouseClicked(point);

        isMousePressed=true;
    }
    else if(event->button()==Qt::RightButton)
    {
         startPoint=event->pos();
         isRightMousePressed=true;
    }
    QGraphicsView::mousePressEvent(event);
}

void QWGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton)
    {
        isMousePressed=false;
    }
}



void QWGraphicsView::wheelEvent(QWheelEvent *even)
{
    if(even->delta()<0&&zoomFactor<=0.05)
    {
        return;
    }
    else
    {
        if(even->delta()>0)
        {
            double newZoomFactor=zoomFactor+(zoomFactor/5.0);
            scale(newZoomFactor/zoomFactor,newZoomFactor/zoomFactor);
            zoomFactor=newZoomFactor;
        }
        else
        {
            double newZoomFactor=zoomFactor-(zoomFactor/5.0);
            scale(newZoomFactor/zoomFactor,newZoomFactor/zoomFactor);
            zoomFactor=newZoomFactor;
        }
    }
}


void QWGraphicsView::setZoomFactor(double newZoomFactor)
{
    scale(newZoomFactor/zoomFactor,newZoomFactor/zoomFactor);
    zoomFactor=newZoomFactor;
}


